#!/user/bin/python
#!conding=utf8
 
import os
import json
# g = os.walk("decorator")
 
 
# for path,d,filelist in g:
#   # print(d)
#   for filename in filelist:
#     print(os.path.join(path, filename))
# print("test")
def processShop(source):
  tmpRes = {}
  for sourceId, sourceDetail in source.items():
    # tmpRes[sourceDetail[]]
    # print("check soruce detail: " + str(sourceDetail));
    if(sourceDetail["gold_price"] == ""):
      sourceDetail["price_type"] = "diamond"
      sourceDetail["price"] = int(sourceDetail["diamond_price"])
    else:
      sourceDetail["price_type"] = "gold"
      sourceDetail["price"] = int(sourceDetail["gold_price"])

    sourceDetail.pop('gold_price', None)
    sourceDetail.pop('diamond_price', None)      
    tmpRes[sourceId] = sourceDetail
  return tmpRes

def processBuildingSkin(source):
  tmpRes = {}
  for sourceId, sourceDetail in source.items():
    if(not sourceDetail["building_id"] in tmpRes):
      tmpRes[sourceDetail["building_id"]] = []
    tmpRes[sourceDetail["building_id"]].append(sourceId)
  
  source["building_list"] = tmpRes
  return source

def processDecoration(source):
  tmpRes = {}
  for sourceId, sourceDetail in source.items():
    for matching_building in sourceDetail["matching_building"]:
      if(not matching_building in tmpRes):
        tmpRes[matching_building] = []
      tmpRes[matching_building].append(sourceId)
  
  source["building_list"] = tmpRes
  return source

def processRooms(source):
  tmpRes = {}
  for sourceId, sourceDetail in source.items():
    for matching_building in sourceDetail["matching_building"]:
      if(not matching_building in tmpRes):
        tmpRes[matching_building] = []
      tmpRes[matching_building].append(sourceId)
  
  source["building_list"] = tmpRes
  return source


def processStrings(source):
  tmpRes = {}
  for sourceId, sourceDetail in source.items():
    print("process string detail:" + str(sourceDetail))
    source[sourceId] = sourceDetail['des']
  return source

def processRestRooms(source):
  tmpRes = {}
  for sourceId, sourceDetail in source.items():
    for matching_building in sourceDetail["matching_building"]:
      if(not matching_building in tmpRes):
        tmpRes[matching_building] = []
      tmpRes[matching_building].append(sourceId)
  # print("process rest rooms:" + str(tmpRes))
  source["building_list"] = tmpRes
  return source


def finalProcess():
  # after build
  buildings = loadJsonFile("building") 
  building_skins = loadJsonFile("building_skin")
  building_decorator = loadJsonFile("decoration")
  rooms = loadJsonFile("room")
  rest_rooms = loadJsonFile("rest_room")

  #print("check building skins:"+str(building_skins))
  my_building_skins = building_skins["building_list"]
  my_building_decorators = building_decorator["building_list"]  
  my_building_rooms = rooms["building_list"]
  my_building_rest_rooms = rest_rooms["building_list"]
  all_buildings = []
  # print("my building decoraton:" + str(my_building_decorators))
  for building_id, building_data in buildings.items():
    # building_list[building_id].remove(buildingData["skin_id"])
    all_buildings.append(building_id)
    buildings[building_id]["skin_list"] = my_building_skins[building_id]
    buildings[building_id]["decorator_list"] = my_building_decorators["all"]
    buildings[building_id]["room_list"] = my_building_rooms["all"] 
    buildings[building_id]["rest_room_list"] = my_building_rest_rooms["all"] 

    # print("check bulding id:" + building_id + "," + str(my_building_decorators["all"]))
    if(building_id in my_building_decorators):
      #print("check building id 2:" + str(my_building_decorators[building_id]) + "<====>" + str(my_building_rooms[building_id]))
      if building_id in my_building_decorators.keys():
        buildings[building_id]["decorator_list"] = buildings[building_id]["decorator_list"] + my_building_decorators[building_id]
      if building_id in my_building_rooms.keys():
        buildings[building_id]["room_list"] = buildings[building_id]["room_list"] + my_building_rooms[building_id]
      if building_id in my_building_rest_rooms.keys():
        buildings[building_id]["rest_room_list"] = buildings[building_id]["rest_room_list"] + my_building_rest_rooms[building_id]

  buildings["all_list"] = all_buildings
  saveJsonFile("building", buildings)
  building_skins.pop("building_list", None)
  saveJsonFile("building_skin", building_skins)
  building_decorator.pop("building_list", None)
  saveJsonFile("decoration", building_decorator)
  rooms.pop("building_list", None)
  saveJsonFile("room", rooms)
  rest_rooms.pop("building_list", None)
  saveJsonFile("rest_room", rest_rooms)



def loadJsonFile(fileName):  
  data = {}
  with open("json/"+fileName +".json") as data_file:    
    data = json.load(data_file)
  return data

def saveJsonFile(fileName, data):
  with open("json/"+fileName+".json", 'w', encoding='utf8') as outfile:
          json.dump(data, outfile,  ensure_ascii=False, sort_keys=True, indent=2)# 排序并且缩进两个字符输出

def listFiles(path):
  filelist =  os.listdir(path)
 
  for filename in filelist:
    filepath = os.path.join(path, filename)
    if os.path.isdir(filepath):
      print("dir:"+filepath)
    else:
      # print("check file :" + filename)
      fileNames = filename.split(".")
      # print("check file name:" + str(fileNames))
      with open(filepath) as f:
        source = json.load(f)
      tmpRes = {}
      updateJson = 1
      for sourceDetail in source:
        if isinstance(sourceDetail,dict):
          if 'id' in sourceDetail:
            tmpRes[sourceDetail['id']] = sourceDetail  
          else:
            print("empty id")
            updateJson = 0
            break
      # print("check finel name:" + str(fileNames))
      # print("check finel name res:" + str(tmpRes))      
      if fileNames[0] == "shop":
        tmpRes = processShop(tmpRes)
      elif fileNames[0] == "building_skin":
        tmpRes = processBuildingSkin(tmpRes)
      elif fileNames[0] == "decoration":
        tmpRes = processDecoration(tmpRes)
      elif fileNames[0] == "room":
        tmpRes = processRooms(tmpRes)
      elif fileNames[0] == "rest_room":
        tmpRes = processRestRooms(tmpRes)
      elif fileNames[0] == "string":
        tmpRes = processStrings(tmpRes)

      # print("check source:"+str(sourceDetail))
      print("check final data:" + str(tmpRes) + " " + str(fileNames))
      if updateJson:
        saveJsonFile(fileNames[0], tmpRes)
    #end if
  #end for
    
  finalProcess()
  #end def listFiles
        # with open(filepath, 'w', encoding='utf8') as outfile:
        #   json.dump(tmpRes, outfile,  ensure_ascii=False, sort_keys=True, indent=2)# 排序并且缩进两个字符输出




listFiles("json")